package com.ma4567.remotecontroller.ffmpegManager;


import com.ma4567.remotecontroller.util.NginxController;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;

public class ffmpegController implements Runnable {
    public static boolean Streaming = false;
    public static Process ffmpegProcess = null;

    public static void StartStream(){
        if(!Streaming){
            try {
                String myExe = "cmd /c ffmpeg.exe -f gdigrab -i desktop -vcodec libx264 -f flv rtmp://localhost:1935/live/live";

                File dir = new File("D:\\IDE\\ffmpeg\\bin");
                String[] str = new String[] {};

                ffmpegProcess = Runtime.getRuntime().exec(myExe, str, dir);
                BufferedReader stdInput = new BufferedReader(new InputStreamReader(ffmpegProcess.getInputStream()));
                BufferedReader stdError = new BufferedReader(new InputStreamReader(ffmpegProcess.getErrorStream()));
                String s;

                while ((s = stdInput.readLine()) != null) System.out.println(s);
                while ((s = stdError.readLine()) != null) System.err.println(s);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    public static void StopStream(){
        if(ffmpegProcess != null){
            ffmpegProcess.destroy();
            NginxController.StopNginx();
        }
    }

    public static void main(String[] args) throws IOException {
        NginxController.StartNginx();
        String myExe = "cmd.exe /c start D:\\IDE\\ffmpeg\\bin\\start.bat";

        File dir = new File("D:\\IDE\\ffmpeg\\bin");
        String[] str = new String[] {};

        ffmpegProcess = Runtime.getRuntime().exec(myExe, str, dir);
        BufferedReader stdInput = new BufferedReader(new InputStreamReader(ffmpegProcess.getInputStream()));
        BufferedReader stdError = new BufferedReader(new InputStreamReader(ffmpegProcess.getErrorStream()));
        String s;

        while ((s = stdInput.readLine()) != null) System.out.println(s);
        while ((s = stdError.readLine()) != null) System.err.println(s);
    }

    public void run() {
        StartStream();
    }
}
